﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using bChatServerDAL;
using bChatServerComm;
using ServerDALDll;

namespace bChatServer
{
    internal static class ApplicationController
    {

        #region fields

        public static Dictionary<Channel, List<Session>> Channels { get; private set; }
        public static List<Session> ActiveSessions { get; private set; }

        #endregion

        #region class onlies

        internal static void Init(string InterfacePort="8500")
        {
            RegisterEvents();

            CommunicationMaster.Init(InterfacePort);

            ServerDAL.Init();

            
            LoadChannels();

        }

        internal static void RegisterEvents()
        {
            CommunicationMaster.CommWrapperNotify += new CommunicationMaster.CommWrapperNotifyHandler(CommunicationMaster_CommWrapperNotify);

            CommunicationMaster.CommWrapperRequest_Register += new CommunicationMaster.CommWrapperRegisterHandler(CommunicationMaster_CommWrapperRequest_Register);


            ServerDAL.ServerDALNotifyEvent += new ServerDAL.ServerDALNotifyHandler(Instance_ServerDALNotifyEvent);
        }

        internal static void LoadChannels()
        {
            var channels = ServerDAL.GetChannels();

            foreach (var item in channels)
            {
                Channels.Add(item, new List<Session>());
            }
        }

        #endregion





        #region Comm event handlers


        static void CommunicationMaster_CommWrapperRequest_Register(object sender, Request_RegisterEventArgs e)
        {
            List<string> Errors = new List<string>();

            if (ServerDAL.IsUserExist(e.UserName)) Errors.Add("user_exists");
            if (!ServerDAL.IsEmailUnique(e.Email)) Errors.Add("email_exists");

            //barom megoldás, át lehetne gondolni valami appconfigból regexet vagy akármit
            if (e.Password.Length < 6) Errors.Add("password_format");

            if (Errors.Count == 0)
            {
                if (!ServerDAL.RegisterUser(e.UserName, e.Email, e.Password, e.Description))
                {
                    Errors.Add("register_error");
                }
            }

            CommunicationMaster.Response_Register(Errors.Count == 0, Errors, (Guid)e.ConnectionID);


        }

        static void CommunicationMaster_CommWrapperNotify(object sender, CommWrapperServiceMessageEventArgs e)
        {
            ServerLog.LogEvent(e.Type, "Comm", e.Operation, e.Comment, e.Ex);
        }

        #endregion

        #region DAL event handlers

        static void Instance_ServerDALNotifyEvent(object sender, ServerDALNotifyEventArgs e)
        {
            ServerLog.LogEvent(e.Type, "DAL", e.Operation, e.Comment, e.Ex);
        }


        #endregion



    }
}
